<template>
  <div class="rental-form">
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="100px"
    >
      <el-form-item label="房源信息">
        <div class="house-info">
          <el-image
            :src="house.imageUrl"
            fit="cover"
            class="house-image"
          />
          <div class="info">
            <h3>{{ house.title }}</h3>
            <p>{{ house.address }}</p>
            <div class="tags">
              <el-tag size="small">{{ house.houseType }}</el-tag>
              <el-tag size="small" type="success">{{ house.rentalType }}</el-tag>
            </div>
          </div>
        </div>
      </el-form-item>

      <el-form-item label="租期" prop="rentalPeriod">
        <el-date-picker
          v-model="form.rentalPeriod"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :disabled-date="disabledDate"
          @change="handleDateChange"
        />
      </el-form-item>

      <el-form-item label="月租金">
        <div class="price-info">
          <span class="price">¥{{ monthlyRent }}</span>
          <span class="original-price" v-if="house.originalPrice">
            原价：¥{{ house.originalPrice }}/月
          </span>
        </div>
      </el-form-item>

      <el-form-item label="押金">
        <div class="deposit-info">
          <span class="deposit">¥{{ deposit }}</span>
          <el-tag
            v-if="isDepositFree"
            type="success"
            size="small"
          >
            免押金
          </el-tag>
        </div>
      </el-form-item>

      <el-form-item label="总金额">
        <div class="total-info">
          <span class="total">¥{{ totalAmount }}</span>
          <span class="period">（{{ rentalMonths }}个月）</span>
        </div>
      </el-form-item>

      <el-form-item label="联系人" prop="contactName">
        <el-input v-model="form.contactName" placeholder="请输入联系人姓名" />
      </el-form-item>

      <el-form-item label="联系电话" prop="contactPhone">
        <el-input v-model="form.contactPhone" placeholder="请输入联系电话" />
      </el-form-item>

      <el-form-item label="备注" prop="remark">
        <el-input
          v-model="form.remark"
          type="textarea"
          :rows="3"
          placeholder="请输入备注信息"
        />
      </el-form-item>

      <el-form-item>
        <div class="form-actions">
          <el-button @click="$emit('cancel')">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确认租房</el-button>
        </div>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
import { ref, computed, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { calculateRent, calculateDeposit } from '@/api/rental'

const props = defineProps({
  house: {
    type: Object,
    required: true
  },
  userCreditScore: {
    type: Number,
    required: true
  }
})

const emit = defineEmits(['submit', 'cancel'])

const formRef = ref(null)
const form = ref({
  rentalPeriod: [],
  contactName: '',
  contactPhone: '',
  remark: ''
})

const rules = {
  rentalPeriod: [
    { required: true, message: '请选择租期', trigger: 'change' }
  ],
  contactName: [
    { required: true, message: '请输入联系人姓名', trigger: 'blur' }
  ],
  contactPhone: [
    { required: true, message: '请输入联系电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ]
}

// 计算属性
const rentalMonths = computed(() => {
  if (!form.value.rentalPeriod || form.value.rentalPeriod.length !== 2) {
    return 0
  }
  const [start, end] = form.value.rentalPeriod
  const months = (end.getFullYear() - start.getFullYear()) * 12 +
    (end.getMonth() - start.getMonth())
  return months
})

const monthlyRent = computed(() => {
  return props.house.currentPrice
})

const deposit = computed(() => {
  return props.house.currentPrice
})

const isDepositFree = computed(() => {
  return props.userCreditScore >= 700
})

const totalAmount = computed(() => {
  return monthlyRent.value * rentalMonths.value + (isDepositFree.value ? 0 : deposit.value)
})

// 方法
const disabledDate = (time) => {
  return time.getTime() < Date.now() - 8.64e7
}

const handleDateChange = (val) => {
  if (val && val.length === 2) {
    const [start, end] = val
    if (end.getTime() - start.getTime() < 30 * 24 * 60 * 60 * 1000) {
      ElMessage.warning('最短租期为30天')
      form.value.rentalPeriod = []
    }
  }
}

const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    
    const rentalData = {
      houseId: props.house.id,
      startDate: form.value.rentalPeriod[0],
      endDate: form.value.rentalPeriod[1],
      contactName: form.value.contactName,
      contactPhone: form.value.contactPhone,
      remark: form.value.remark,
      monthlyRent: monthlyRent.value,
      deposit: deposit.value,
      totalAmount: totalAmount.value,
      isDepositFree: isDepositFree.value
    }
    
    emit('submit', rentalData)
  } catch (error) {
    ElMessage.error('请完善表单信息')
  }
}
</script>

<style lang="scss" scoped>
.rental-form {
  .house-info {
    display: flex;
    gap: 20px;
    padding: 10px;
    background-color: #f5f7fa;
    border-radius: 4px;

    .house-image {
      width: 120px;
      height: 90px;
      border-radius: 4px;
    }

    .info {
      flex: 1;

      h3 {
        margin: 0 0 10px;
        font-size: 16px;
        color: #303133;
      }

      p {
        margin: 0 0 10px;
        color: #606266;
        font-size: 14px;
      }

      .tags {
        .el-tag {
          margin-right: 5px;
        }
      }
    }
  }

  .price-info,
  .deposit-info,
  .total-info {
    display: flex;
    align-items: center;
    gap: 10px;

    .price,
    .deposit,
    .total {
      color: #f56c6c;
      font-size: 20px;
      font-weight: bold;
    }

    .original-price {
      color: #909399;
      text-decoration: line-through;
    }

    .period {
      color: #909399;
    }
  }

  .form-actions {
    display: flex;
    justify-content: flex-end;
    gap: 10px;
  }
}
</style> 